package com.sl.diary.activity;

import java.util.ArrayList;
import java.util.List;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.sl.diary.R;
import com.sl.diary.db.DBManager;
import com.sl.diary.model.PointModel;
import com.sl.diary.network.LocationUpdate;
import com.sl.diary.network.LocationUpdate.LocationUpdateListener;
import com.sl.diary.util.Util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class A001_A002MainMap extends FragmentActivity
					implements LocationUpdateListener,
								OnClickListener{
	/** The tag. */
	private static String TAG = "A001_A002MainMap";
	
	// location
	private LocationManager locationManager;
	private LatLng 			currentLocation;
	private LatLngBounds	regionBound;
	private boolean 		endExecute = false;
	private static final int MAP_ZOOM_SIZE = 16;
	
	// layout for a001
	private RelativeLayout 	a001_layout_splashscreen;
	private ProgressBar 	a001_progress_loading;
	private TextView 		a001_txt_skip, a001_txt_version;
	private ImageView 		a001_logo;
	
	// layout for a002
	private RelativeLayout 	a002_layout_main_map, a002_layout_header;
	private GoogleMap 		a002_fragment_map;
	private ImageButton		a002_btn_back, a002_btn_add_travel,
							a002_btn_show_type, a002_btn_show_photo;
	/** The db. */
	private DBManager db;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a001_a002_main_map);
		
		db = new DBManager(getApplicationContext());
		db.open();
		
		initView();
		
		if(Util.isNetworkConnected(this)) {
			locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			startNewLocationUpdate();
		} else {
			showDialogError(String.format(getResources()
					.getString(R.string.connection_error)));
		}
	}
	
	private void initView(){
		a001_layout_splashscreen 	= (RelativeLayout) findViewById(R.id.a001_layout_splashscreen);
		a001_progress_loading 		= (ProgressBar) findViewById(R.id.a001_progress_loading);
		a001_txt_skip 				= (TextView) findViewById(R.id.a001_txt_skip);
		a001_txt_version 			= (TextView) findViewById(R.id.a001_txt_version);
		a001_logo 					= (ImageView) findViewById(R.id.a001_logo);
		
		a002_layout_main_map		= (RelativeLayout) findViewById(R.id.a002_layout_main_map);
		a002_layout_header			= (RelativeLayout) findViewById(R.id.a002_layout_header);
		a002_btn_back				= (ImageButton) findViewById(R.id.a002_btn_back);
		a002_btn_add_travel			= (ImageButton) findViewById(R.id.a002_btn_add_travel);
		a002_btn_show_type			= (ImageButton) findViewById(R.id.a002_btn_show_type);
		a002_btn_show_photo			= (ImageButton) findViewById(R.id.a002_btn_show_photo);
		
		SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.a002_fragment_map);
		a002_fragment_map = fragment.getMap();
		
		/*
		 * set animation for layout a001
		 */
		final Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
		animFadeIn.setAnimationListener(new Animation.AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				if(endExecute) {
					startA002MainMapScreen();
				} else {
					endExecute = true;
				}
			}
		});
		
		final Animation animBounce = AnimationUtils.loadAnimation(this, R.anim.bounce);
		animBounce.setAnimationListener(new Animation.AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				a001_txt_version.startAnimation(animFadeIn);
				a001_txt_version.setVisibility(View.VISIBLE);
			}
		});
		
		a001_logo.startAnimation(animBounce);
		
		// get version name
		PackageManager manager = this.getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			a001_txt_version.setText("Version " + info.versionName);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//Update new
	/** The location updater. */
	LocationUpdate locationUpdater;
	
	/**
	 * Start new location update.
	 */
	private void startNewLocationUpdate() {
		if (locationUpdater != null)
			if (!locationUpdater.isStopUpdating())
				locationUpdater.stopUpdate();

		locationUpdater = null;
		locationUpdater = new LocationUpdate(this);
		locationUpdater.setLocationUpdateListener(this);
		locationUpdater.startAllUpdate();
	}
	
	/**
	 * Stop location update.
	 */
	private void stopLocationUpdate() {
		if (locationUpdater != null)
			if (!locationUpdater.isStopUpdating())
				locationUpdater.stopUpdate();
	}
	
	@Override
	public void onLocationSuccess(Location location) {
		this.currentLocation = new LatLng(location.getLatitude(), 
				location.getLongitude());
		moveCamera(currentLocation);
		
		// get DB
		List<PointModel> pointDB = db.getAllPoint();
		ArrayList<PointModel> pointList = Util.calculateNearestPoint(pointDB, location);
		
		if(endExecute) {
			
//			startA002MainMapScreen();			
		} else {
			endExecute = true;
			
		}
	}

	@Override
	public void onLocationFail(String error) {
		showDialogError(String.format(getResources()
				.getString(R.string.connection_error)));
	}
	
	private void moveCamera(LatLng location) {
		CameraUpdate camera = CameraUpdateFactory
				.newCameraPosition(new CameraPosition.Builder()
					.target(location)
					.zoom(MAP_ZOOM_SIZE).build());
		a002_fragment_map.animateCamera(camera);
		
		// get latlngbounds
		regionBound = a002_fragment_map.getProjection().getVisibleRegion().latLngBounds;
		
	}
	
	/**
	 * Show dialog error.
	 *
	 * @param message the message
	 */
	private void showDialogError(String message){
		final AlertDialog alerDlgErrorBase = new AlertDialog.Builder(this).create();
		alerDlgErrorBase.setTitle(R.string.error);
		alerDlgErrorBase.setMessage(message);

		// Set button cancel
		alerDlgErrorBase.setButton(String.format(getResources()
							.getString(R.string.lbl_ok)), 
							new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alerDlgErrorBase.dismiss();
				finish();
				return;
			}
		});
		if(this.isFinishing() == false){
			alerDlgErrorBase.show();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            	unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
        ((ViewGroup) view).removeAllViews();
        }
    }
	
	private void startA002MainMapScreen() {
		a001_layout_splashscreen.setVisibility(View.GONE);
		stopLocationUpdate();
		unbindDrawables(findViewById(R.id.a001_layout_splashscreen));
		System.gc();
	}
}
